﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Viettel.VOFFICE.DAO.DAL.Paging;
using Viettel.VOFFICE.DAO.Models;

namespace Viettel.VOFFICE.DAO.DAL.Repository
{
    /// <summary>
    /// thư viện dùng để lưu các biểu mẫu, tờ mẫu trình
    /// </summary>
    public class LibraryRepository : IRepository<Library>
    {
        private VOFFICEContext context;
        public LibraryRepository(VOFFICEContext context)
        {
            if (context == null)
            {
                throw new Exception("Context must be init");
            }
            this.context = context;
        }
        public IEnumerable<Library> Get()
        {
            return context.Libraries.OrderByDescending(o => o.UpdatedAt).Select(o => o);
        }

        public Library GetById(object id)
        {
            return context.Libraries.Find(int.Parse(id.ToString()));
        }

        public IEnumerable<Library> FindByName(object s)
        {
            throw new NotImplementedException();
        }

        public void Insert(Library T)
        {
            context.Libraries.Add(T);
            Save();
        }

        public void Delete(object id)
        {
            var item = GetById(id);
            if (item!=null)
            {
                context.Libraries.Attach(item);
                context.Libraries.Remove(item);
                Save();
            }
        }

        public void Delete(Library T)
        {
            if (T !=null)
            {
                context.Libraries.Attach(T);
                context.Libraries.Remove(T);
                Save();
            }
        }

        public void Update(Library T)
        {
            context.Entry(T).State= EntityState.Modified;
            Save();
        }

        public void Save()
        {
            context.SaveChanges();
        }

        public PagedList<Library> GetPaging(int pageIndex, int pageSize)
        {
            return context.Libraries.OrderByDescending(o => o.CreatedAt).Paginate(pageIndex, pageSize);
        }


        /// <summary>
        /// Lấy toàn bộ bản ghi theo giá trị active
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public IEnumerable<Library> GetByActive(bool p)
        {
            if (p == true)
            {
                return context.Libraries.Where(o => o.IsActive == p);
            }
            else
            {
                return context.Libraries.Where(o => o.IsActive == null || o.IsActive == p);
            }
        }
    }
}
